<?php
include_once APP_FILES.'password.php';

session_start();

abstract class Auth {
    private static $isLogged;



    static function login() {
        self::_start();
        $pass = Arr::getValue($_POST, 'pass', '-');
        $token = Arr::getValue($_POST, 'token', '-');

        if (self::_checkPass($pass, $token)) {
            self::_setNewExpiry ();
            $_SESSION['isLogged'] = true;
        }

        return self::isLogged();
    }


    static function logout() {
        self::_start();
        self::_end();
    }


    static function isLogged() {
        self::_start();

        if (is_null(Arr::getValue($_SESSION, 'exp'))) self::_setNewExpiry ();
        if (self::_expired()) {
            self::_end();
            self::_start();
        }

        return self::$isLogged;
    }


    public static function getToken () {
        $exp = Arr::getValue($_SESSION, 'exp', 0);
        return md5($exp);
    }













    private static function _start() {
        if (is_null(self::$isLogged)) @session_start(); // it's generate E_NOTICE when session.autostart is on
        self::$isLogged = Arr::getValue($_SESSION, 'isLogged', FALSE);
    }


    private static function _end() {
        $_SESSION = array();
        self::$isLogged = false;
    }


    private static function _checkPass($pass, $token) {
        if (self::$isLogged) return true;
        $md5exp = self::getToken();

        if ($md5exp != $token) return false;
        $md5pass = md5(ADMIN_PASS.$md5exp);

        return ($pass == $md5pass);
    }


    private static function _setNewExpiry() {
        $_SESSION['exp'] = time() + 7200;
    }

    private static function _expired() {
        return (time() > Arr::getValue($_SESSION, 'exp', 0));
    }









    public static function loginForm($modal=false) {
        $params = array(
            'token' => self::getToken()
        );
        $page = $modal? 'forms/form_login_modal.php' : 'forms/form_login.php';
        include APP_PAGE_PARTS.$page;
    }
}

?>